import {
  Empty,
  Typography,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Spin,
  message,
} from "antd";
import React, { FC, useState } from "react";
import styles from "./common.module.scss";

import { ExclamationCircleOutlined } from "@ant-design/icons";
import ListSearch from "../../components/ListSearch";
import useLoadQuestionData from "../../hooks/useLoadQuestionListData";
import ListPage from "../../components/ListPage";
import {
  updateQuestionService,
  deleteQuestionService,
} from "../../services/question";
import { useRequest } from "ahooks";

const { Title } = Typography;
const { confirm } = Modal;

const Trash: FC = () => {
  const {
    data = {},
    loading,
    refresh,
  } = useLoadQuestionData({ isDeleted: true });
  const { list = [], total = 0 } = data;

  const tableColumns = [
    {
      title: "标题",
      dataIndex: "title",
      // key:'title'   循环列的key  会默认取dataIndex的值
    },
    {
      title: "是否发布",
      dataIndex: "isPublished",
      //根据数据源，返回自定义的tsx片段
      render: (isPublished: boolean) => {
        return isPublished ? (
          <Tag color="processing">已发布</Tag>
        ) : (
          <Tag> 未发布</Tag>
        );
      },
    },
    {
      title: "答卷数量",
      dataIndex: "answerCount",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
    },
  ];
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  // 彻底删除
  const { run: deleteQuestion } = useRequest(
    async () => await deleteQuestionService(selectedIds),
    {
      manual: true,
      onSuccess() {
        message.success("删除成功");
        refresh(); //手动刷新列表
        setSelectedIds([]);
      },
    }
  );
  function del() {
    confirm({
      title: "确定彻底删除该问卷？",
      icon: <ExclamationCircleOutlined />,
      content: "删除以后不能找回",
      onOk: deleteQuestion,
    });
  }
  // 恢复
  const { loading: recoverLoading, run: recover } = useRequest(
    async () => {
      // for await of  将异步的代码同步遍历
      for await (const id of selectedIds) {
        await updateQuestionService(id, { isDeleted: false });
      }
    },
    {
      manual: true,
      debounceWait: 500, //防抖
      onSuccess() {
        message.success("恢复成功");
        refresh(); //手动刷新列表
        setSelectedIds([]);
      },
    }
  );
  // 可以吧jsx片段定义成一个变量
  const TableElem = (
    <>
      <div style={{ marginBottom: "16px" }}>
        <Space>
          <Button
            type="primary"
            disabled={selectedIds.length === 0 || recoverLoading}
            onClick={recover}
          >
            恢复
          </Button>
          <Button danger disabled={selectedIds.length === 0} onClick={del}>
            彻底删除
          </Button>
        </Space>
      </div>
      <Table
        dataSource={list}
        columns={tableColumns}
        pagination={false}
        // rowkey 告诉table 行的key字段  ;;; rowKey 可以指定row selection 获取哪些数据
        rowKey={(q) => q._id}
        rowSelection={{
          type: "checkbox",
          onChange: (selectedRowKeys) => {
            setSelectedIds(selectedRowKeys as string[]);
          },
        }}
      />
    </>
  );

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>回收站</Title>
        </div>
        <div className={styles.right}>
          <ListSearch></ListSearch>
        </div>
      </div>
      <div className={styles.container}>
        {loading && (
          <div style={{ textAlign: "center" }}>
            <Spin />
          </div>
        )}
        {!loading && list.length === 0 && <Empty description="暂无数据" />}
        {!loading && list.length > 0 && TableElem}
      </div>
      <div className={styles.footer}>
        <ListPage total={total} />
      </div>
    </>
  );
};

export default Trash;
